from django.shortcuts import render
from django.http import HttpRequest, HttpResponse, HttpResponseBadRequest, JsonResponse
import simplejson
from .models import User
from app.settings import SECRET_KEY
import jwt
import datetime
import bcrypt
from utls import getlogger

log = getlogger('user')

# 定义时间
EXP_TIMNE = 10 * 60


def get_token(user_id):
    return jwt.encode(payload={'user_id': user_id, 'exp': int(datetime.datetime.now().timestamp()) + EXP_TIMNE}
                      , key=SECRET_KEY, algorithm='HS256').decode()


def authontoken(view):
    def __wapper(request: HttpRequest):
        token = request.META.get('HTTP_JWT')
        if token:
            try:
                payload = jwt.decode(token, SECRET_KEY, algorithm='HS256')  # 此处便有处理机制来处理过期
                user = User.objects.filter(pk=payload['user_id']).get()  # 获取user_id，若存在，则表明此token是当前用户的token
                request.user_id = user.id
                log.info('token 合法校验通过')
            except  Exception as e:
                log.error(e)
                return HttpResponseBadRequest(b'token  auth  failed')
        else:
            log.error('未登录过，请登录')
        return view(request)

    return __wapper


def reg(request: HttpRequest):
    try:
        payload = simplejson.loads(request.body)
        email = payload['email']
        print(email)
        query = User.objects.filter(email=email)  # 获取邮箱信息
        if query:  # 若邮箱存在
            return HttpResponseBadRequest(b'email  exist')
        user = User()
        name = payload['name']
        passowrd = payload['password'].encode()
        print(email, name, passowrd)
        user.name = name
        user.password = bcrypt.hashpw(passowrd, bcrypt.gensalt()).decode()  # 获取加密后的password信息
        user.email = email
        try:
            user.save()
            log.info('用户{}注册成功'.format(user.name))
            return JsonResponse({'userinfo': {
                'USER_ID': user.id,
                'name': user.name,
                'email': user.email,
            }, 'token': get_token(user.id)})
        except  Exception as e:
            log.error(e)
            log.error("用户{}注册失败".format(user.name))
            return HttpResponseBadRequest(b'data  insert  failed')
    except  Exception  as e:
        log.error(e)
        return HttpResponseBadRequest(b'paraments  type  not  legal')


@authontoken
def login(request: HttpRequest):
    try:
        payload = simplejson.loads(request.body)  # 邮箱和密码,并且能够获取token，需要先判断邮箱是否存在，若不存在，则直接报错
        email = payload['email']
        user = User.objects.filter(email=email).get()
        if not user.id:
            return HttpResponseBadRequest("email :{}  not exist".format(email).encode())
        password = payload['password']
        if bcrypt.checkpw(password.encode(), user.password.encode()):
            log.info("用户{}登录成功".format(user.name))
            return JsonResponse({
                "userinfo": {
                    "user_id": user.id,
                    "user_name": user.name,
                    "user_email": user.email,
                },
                "token": get_token(user.id)
            })
        else:
            log.error("用户{}登录失败".format(user.name))
            return HttpResponseBadRequest(b'password  failed')
    except  Exception  as e:
        log.error(e)
        log.error("用户{}登录失败，邮箱{}不存在")
        return HttpResponseBadRequest(b'email  failed')
